package web

import (
	"context"

	"gitee.com/crack007/goose/gscore"
	"gitee.com/crack007/goose/gsutil"
	"github.com/spf13/cobra"
)

type HttpServerBuilder struct {
	Port         uint16
	ServerHandle IHttpServerHandle
	gscore.BaseBuilder
	ServerName string
}

func NewHttpServerBuilder(serverHandle IHttpServerHandle) *HttpServerBuilder {
	ctx, cancelFunc := context.WithCancel(context.Background())
	return &HttpServerBuilder{
		Port:         0,
		ServerHandle: serverHandle,
		BaseBuilder: gscore.BaseBuilder{
			Ctx:        ctx,
			CancelFunc: cancelFunc,
			CobraCmd:   &cobra.Command{},
		},
		ServerName: "",
	}
}

func (x *HttpServerBuilder) SetPort(Port uint16) {
	x.Port = Port
}

func (x *HttpServerBuilder) GetServerName() string {
	return x.ServerName
}

func (x *HttpServerBuilder) SetServerName(serverName string) {
	x.ServerName = serverName
}

func (x *HttpServerBuilder) GetHandle() gscore.IHandle {
	return x.ServerHandle
}

func (x *HttpServerBuilder) Build() (gscore.IServer, error) {
	_httpServer := &HttpServer{
		port:    x.Port,
		Builder: x,
		BaseServer: gscore.BaseServer{
			IsGraceful: true,
			Ctx:        x.GetCtx(),
			Cancel:     x.GetCancelFunc(),
			WorkPath:   gsutil.RuntimeUtil.GetWorkPath(),
		},
	}
	_httpServer.SetServerName(x.ServerName)
	_httpServer.SetCobraCmd(x.GetCobraCmd())
	return _httpServer, nil
}

func (x *HttpServerBuilder) EnablePortFlag(defaultPort uint16) *HttpServerBuilder {
	x.GetCobraCmd().PersistentFlags().Uint16VarP(&x.Port, "port", "p", defaultPort, "http server port")
	return x
}
